package presentation;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;

import db.Comment;
import db.DbUtils;
import db.Picture;

/**
 * Servlet implementation class for Servlet: EditPictureServlet
 * 
 */
public class EditPictureServlet extends javax.servlet.http.HttpServlet
		implements javax.servlet.Servlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		Long imageId = Long.parseLong(request.getParameter("image"));
		String newTitle = request.getParameter("title");
		Session hbSession = DbUtils.startSession();
		if (newTitle == null) {
			response.sendRedirect("Edit.jsp?image=" + imageId);
			HttpSession session = request.getSession();
			Picture pic=DbUtils.getPicturebyId(hbSession, imageId);;
			session.setAttribute("oldTitle", pic.getPictureTitle());
			session.setAttribute("oldAlbum", pic.getAlbum().getAlbumName());

		} else {
			try {
				Long albumId = Long.parseLong(request.getParameter("album_id"));
				DbUtils.editPicture(hbSession, imageId, newTitle, albumId);
				hbSession.getTransaction().commit();
				response.sendRedirect("ViewPicture.jsp?image=" + imageId);
			} catch (Exception e) {
				if (hbSession != null) {
					hbSession.getTransaction().rollback();
					hbSession.close();
				}
				response.sendRedirect("Error.jsp?msg=pic");
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		doPost(arg0, arg1);
	}
}